package com.contest.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.contest.constant.CommonsConstant;
import com.contest.entity.MerchantInfo;
import com.contest.entity.UserInfo;
import com.contest.service.*;
import com.contest.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;


/**
 * @author yfl
 * @email 617823298@qq.com
 * @date 2017-12-20 16:30:37
 */

@Controller
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private BettingRecordService bettingRecordService;
    @Autowired
    GameInfoService gameInfoService;
    @Autowired
    RaceInfoService raceInfoService;
    @Autowired
    ClanInfoService clanInfoService;
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    RoomInfoService roomInfoService;
    @Autowired
    IdWorker idWorker;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private SessionInfoService sessionInfoService;


    @RequestMapping("/list")
    @ResponseBody
    public PageUtils list(@RequestParam Map<String, Object> param) {
        int page = Integer.parseInt(param.get("page").toString());
        int rows = Integer.parseInt(param.get("rows").toString());
        param.remove("page");
        param.remove("rows");
        EntityWrapper<UserInfo> userInfoEntityWrapper = new EntityWrapper<UserInfo>();
        Set<String> keys = param.keySet();
        for (String key : keys) {
            Object value = param.get(key);
            if (value != null && !"".equals(value)) {
                userInfoEntityWrapper.like(key, value.toString());
            }
        }
        Page<UserInfo> mPage = new Page<UserInfo>(page, rows);
        mPage = userInfoService.selectPage(mPage, userInfoEntityWrapper);
        return new PageUtils(mPage.getRecords(), mPage.getTotal());
    }

    @PostMapping("/save")
    @ResponseBody
    public R save(HttpServletRequest request, @RequestParam("avatar") CommonsMultipartFile avatar, UserInfo userInfo) {
        String saveName = null;
        if (avatar != null && !avatar.getOriginalFilename().equals("")) {
            saveName = FileUtil.uploadFile(request, avatar);
            userInfo.setFdAvatarUrl(saveName);
        }

        userInfo.setFdId(idWorker.nextId() + "");
        userInfo.setFdPwd(MD5Utils.encrypt(userInfo.getFdPwd()));
        Wrapper<UserInfo> w = new EntityWrapper<UserInfo>();
//        w.addFilter("fd_nickname", userInfo.getFdNickname());
        w.eq("fd_nickname", userInfo.getFdNickname());
        UserInfo userInfo1 = userInfoService.selectOne(w);
        if (userInfo1 != null) {
            return R.error("用户名已存在！");
        }
        if (userInfoService.insert(userInfo)) {
            return R.ok("操作成功!");
        } else {
            return R.error("操作失败");
        }
    }

    @GetMapping("/edit/{fdId}")
    public String edit(Model model, @PathVariable("fdId") String fdId) {
        UserInfo userInfo = userInfoService.selectById(fdId);
        model.addAttribute("userInfo", userInfo);
        return "userInfo/edit";
    }

    @GetMapping("/view/{fdId}")
    public String view(Model model, @PathVariable("fdId") String fdId) {
        UserInfo userInfo = userInfoService.getUserDetailByUserId(fdId);
        model.addAttribute("userInfo", userInfo);
        return "userInfo/view";
    }

    @GetMapping("/edit2/{fdId}")
    public String edit2(Model model, @PathVariable("fdId") String fdId) {
        UserInfo userInfo = userInfoService.selectById(fdId);
        model.addAttribute("userInfo", userInfo);
        return "userInfo/recharge";
    }


    @RequestMapping("/getUserInfo")
    @ResponseBody
    public R getUserInfo(String id) {
        UserInfo userInfo = userInfoService.selectById(id);
        return R.ok(userInfo);
    }

    @PostMapping("/remove")
    @ResponseBody
    public R remove(@RequestParam("ids[]") String[] ids) {
        List<String> fdIds = new ArrayList<String>();
        for (String id : ids) {
            fdIds.add(id);
        }
        if (userInfoService.deleteBatchIds(fdIds)) {
            return R.ok("删除成功");
        } else {
            return R.error(-1, "删除失败!");
        }
    }

    @PostMapping("/update")
    @ResponseBody
    public R update(HttpServletRequest request, @RequestParam("avatar") CommonsMultipartFile avatar, UserInfo userInfo) {
        String saveName = null;
        if (avatar != null && !"".equals(avatar.getOriginalFilename())) {
            saveName = FileUtil.uploadFile(request, avatar);
            userInfo.setFdAvatarUrl(saveName);
        }
        if (userInfoService.updateById(userInfo)) {
            return R.ok("更新成功!");
        } else {
            return R.error(-1, "更新失败!");
        }
    }

    @PostMapping("/recharge")
    @ResponseBody
    public R recharge(HttpServletRequest request, UserInfo userInfo) {
        BigDecimal mny = userInfo.getFdOver();
        UserInfo ui = userInfoService.selectById(userInfo.getFdId());
        userInfo.setFdOver(mny.add(ui.getFdOver()));
        userInfo.setFdRechargeTotal(mny.add(ui.getFdOver()));
        if (userInfoService.updateById(userInfo)) {
            return R.ok("充值成功!");
        } else {
            return R.error(-1, "充值失败!");
        }
    }


    @PostMapping("/updateAdmin")
    @ResponseBody
    public R updateAdmin(HttpServletRequest request, UserInfo userInfo) {
        UserInfo userInfo1 = (UserInfo) request.getSession().getAttribute(CommonsConstant.LOGIN_SESSION);
        userInfo.setFdId(userInfo1.getFdId());
        userInfo.setFdPwd(MD5Utils.encrypt(userInfo.getFdPwd()));
        if (userInfoService.updateById(userInfo)) {
            return R.ok("修改成功!");
        } else {
            return R.error(-1, "修改失败!");
        }
    }


    @PostMapping("/client/login")
    @ResponseBody
    public R loginUser(String userName, String pwd, HttpServletRequest request,HttpServletResponse response) {
        String cookiePwd = pwd;
        WsNeed wsNeed = WsNeed.getInstance();
        wsNeed.setIdWorker(idWorker);
        wsNeed.setBettingRecordService(bettingRecordService);
        wsNeed.setClanInfoService(clanInfoService);
        wsNeed.setGameInfoService(gameInfoService);
        //wsNeed.setJedis(redis);
        wsNeed.setRaceInfoService(raceInfoService);
        wsNeed.setRoomInfoService(roomInfoService);
        wsNeed.setUserInfoService(userInfoService);
        wsNeed.setSessionInfoService(sessionInfoService);
        pwd = MD5Utils.encrypt(pwd);
        Wrapper<UserInfo> w = new EntityWrapper<UserInfo>();
        w.addFilter("(fd_nickname={0} or fd_mobile={1})", userName, userName);
        w.addFilter("fd_pwd={0}", pwd);
        UserInfo user = userInfoService.selectOne(w);
        if (user == null) {
            return R.error("用户名或密码错误!");
//            return R.ok(user);
        } else {
            Cookie cookie = new Cookie("userData", userName + "#" + cookiePwd);
            //设置时间为1年
            cookie.setMaxAge(30 * 24 * 3600);
            cookie.setPath("/");
            //把cookie给浏览器
            response.addCookie(cookie);
//
            request.getSession().setAttribute(CommonsConstant.CLIENT_LOGIN_SESSION, user);
            System.out.println("sessionId:==========>>:" + request.getSession().getId());
            return R.ok(user);
        }
    }



    @RequestMapping("/client/getCookie")
    @ResponseBody
    public R getCookie(HttpServletRequest request) {
        Cookie cookies[] = request.getCookies();
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute(CommonsConstant.CLIENT_LOGIN_SESSION);
        Map<String, Object> ret = new HashMap<>();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals("userData")) {
                String s[] = cookie.getValue().split("#");
                ret.put("username",s[0]);
                ret.put("pwd",s[1]);
                return R.ok(ret);
            }
        }
        return R.error();
    }


    @PostMapping("/client/reg")
    @ResponseBody
    public R saveUser(UserInfo userInfo, HttpServletRequest request, HttpServletResponse response) {
        ServletContext app = request.getServletContext();
        String inputCode = request.getParameter("inputCode");
        String code = app.getAttribute(userInfo.getFdMobile()).toString();
        if (!code.equals(inputCode)) {
            return R.error("验证码错误!");
        } else {
            String recommendCode = userInfo.getFdRecommendCode();
            Wrapper<MerchantInfo> w = new EntityWrapper<>();
            w.addFilter("fd_my_code={0}", recommendCode);
            List<MerchantInfo> mi = merchantInfoService.selectList(w);
            if (mi.size() != 0) {
                userInfo.setFdRecommendCode(recommendCode);
                userInfo.setFdMerchant(mi.get(0).getFdId());
                userInfo.setFdMerchantName(mi.get(0).getFdName());
            } else {
                EntityWrapper<UserInfo> infoEntityWrapper = new EntityWrapper<UserInfo>();
                infoEntityWrapper.addFilter("fd_my_code={0}", recommendCode);
                List<UserInfo> userInfoList = userInfoService.selectList(infoEntityWrapper);
                if (userInfoList.size() != 0) {
                    userInfo.setFdMerchant(userInfoList.get(0).getFdMerchant());
                    userInfo.setFdMerchantName(userInfoList.get(0).getFdMerchantName());
                    MerchantInfo mer = merchantInfoService.selectById(userInfoList.get(0).getFdMerchant());
                    userInfo.setFdRecommendCode(mer.getFdMyCode());
                } else {
                    return R.error("推荐码不存在");
                }
            }

            userInfo.setFdId(idWorker.nextId() + "");

            if (userInfo.getFdAvatarUrl() != null && !"".equals(userInfo.getFdAvatarUrl())) {
                userInfo.setFdAvatarUrl(Base64UploadPic.base64UpLoad(userInfo.getFdAvatarUrl(), "image", request, response));
            }
            userInfo.setFdNickname(userInfo.getFdMobile().substring(6));
            userInfo.setFdType(1);
            userInfo.setFdSex(0);
            userInfo.setFdPwd(MD5Utils.encrypt(userInfo.getFdPwd()));
            userInfo.setFdStatus(1);
            userInfo.setFdAvatarUrl("/image/55767d8a-5665-4a74-8202-caef11f1a22b.png");
            if (userInfoService.reg(userInfo)) {
                return R.ok(userInfo);
            } else {
                return R.error("注册失败");
            }
        }
    }

    @PostMapping("/client/checkName")
    @ResponseBody
    public R checkName(String name) {
        EntityWrapper<UserInfo> ew = new EntityWrapper<UserInfo>();
        ew.addFilter("fd_nickname={0}", name);
        List<UserInfo> userInfo = userInfoService.selectList(ew);
        if (userInfo.size() != 0) {
            return R.error("用户名已被占用!");
        } else {
            return R.ok();
        }
    }


    @PostMapping("/client/sendCode")
    @ResponseBody
    public R sendCode(String phone, HttpServletRequest request) {
        if (!"".equals(phone) && !RegexValidateUtil.checkPhone(phone)) {
            return R.error("手机号格式错误");
        }
        EntityWrapper<UserInfo> ew = new EntityWrapper<UserInfo>();
        ew.addFilter("fd_mobile={0}", phone);
        List<UserInfo> userInfo = userInfoService.selectList(ew);
        if (userInfo.size() != 0) {
            return R.error("手机号已被占用!");
        } else {
            ServletContext app = request.getServletContext();
            String code = SmsUtil.sendVerifyCode(phone);
            if (code != null) {
                app.setAttribute(phone, code);
                return R.ok("验证码发送成功,请注意查收!");
            } else {
                return R.error("验证码发送失败!");
            }
        }
    }

    /**
     * 修改头像
     *
     * @param avatar  头像Base64编码
     * @param request
     * @return
     */
    @PostMapping("/client/changeAvatar")
    @ResponseBody
    public R changeAvatar(String avatar, HttpServletRequest request, HttpServletResponse response) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        String path = Base64UploadPic.base64UpLoad(avatar, "image", request, response);
        userInfo.setFdAvatarUrl(path);
        if (userInfoService.updateById(userInfo)) {
            return R.ok("修改成功!");
        } else {
            return R.error("修改失败!");
        }
    }

    /**
     * 修改性别
     * @param sex     性别
     * @param request
     * @return
     */
    @PostMapping("/client/changeSex")
    @ResponseBody
    public R changeSex(Integer sex, HttpServletRequest request) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        userInfo.setFdSex(sex);
        if (userInfoService.updateById(userInfo)) {
            return R.ok("修改成功!");
        } else {
            return R.error("修改失败");
        }
    }

    /**
     * 修改手机号
     *
     * @param request
     * @return
     */
    @PostMapping("/client/changePhoneNum")
    @ResponseBody
    public R changePhoneNum(String phoneNum, String validate, HttpServletRequest request) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        ServletContext app = request.getServletContext();
        String num = String.valueOf(app.getAttribute(phoneNum));
        if (!validate.equals(num)) {
            return R.error("手机验证码错误！");
        }
        app.removeAttribute(phoneNum);
        userInfo.setFdMobile(phoneNum);
        if (userInfoService.updateById(userInfo)) {
            return R.ok("修改成功!");
        } else {
            return R.error("修改失败");
        }
    }


    /**
     * 忘记密码
     *
     * @param request
     * @return
     */
    @PostMapping("/client/forgetPwd")
    @ResponseBody
    public R forgetPwd(String pwd, String validate, String phoneNum, HttpServletRequest request) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        ServletContext app = request.getServletContext();
        String num = String.valueOf(app.getAttribute(phoneNum));
        if (!validate.equals(num)) {
            return R.error("手机验证码错误！");
        }
        app.removeAttribute(phoneNum);
        userInfo.setFdPwd(pwd);
        if (userInfoService.updateById(userInfo)) {
            return R.ok("修改成功!");
        } else {
            return R.error("修改失败");
        }
    }

    /**
     * 修改密码
     *
     * @param oldPwd  旧密码
     * @param newPwd  新密码
     * @param request
     * @return
     */
    @PostMapping("/client/changePwd")
    @ResponseBody
    public R changePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        if (userInfo.getFdPwd().equals(MD5Utils.encrypt(oldPwd))) {
            userInfo.setFdPwd(MD5Utils.encrypt(newPwd));
            if (userInfoService.updateById(userInfo)) {
                return R.ok("密码修改成功!");
            } else {
                return R.error("密码修改失败");
            }
        } else {
            return R.error("旧密码错误!");
        }
    }

    @RequestMapping("/client/changeName")
    @ResponseBody
    public R changeName(String name, HttpServletRequest request) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
        if (name != null && !"".equals(name)) {
            userInfo.setFdNickname(name);
            if (userInfoService.updateById(userInfo)) {
                request.getSession().setAttribute(CommonsConstant.CLIENT_LOGIN_SESSION, userInfo);
                return R.ok(userInfo);
            } else {
                return R.error("修改失败");
            }
        } else {
            return R.error("请输入昵称");
        }

    }

    @PostMapping("/client/userCenter")
    @ResponseBody
    public R sendCode(HttpServletRequest request) {
        UserInfo userInfo = UserLoginUtil.getCurrentUserInfo(request);
//        userInfo = userInfoService.selectById(userInfo.getFdId());
        return R.ok(userInfo);
    }


    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @PostMapping("/client/rePwd")
    @ResponseBody
    public R changePwd(String username, String pwd, String newpwd, HttpServletRequest request) {

        EntityWrapper<UserInfo> userEntityWrapper = new EntityWrapper<UserInfo>();
        userEntityWrapper.addFilter("fd_mobile={0} and fd_pwd={1} and fd_type={2}", username, MD5Utils.encrypt(pwd), 0);
        UserInfo userInfo = userInfoService.selectOne(userEntityWrapper);
        if (userInfo == null) {
            return R.error("账号或密码错误！");
        }
        userInfo.setFdPwd(MD5Utils.encrypt(newpwd));
        if (userInfoService.updateById(userInfo)) {
            return R.ok("密码修改成功!");
        } else {
            return R.error("密码修改失败");
        }

    }

}

